package com.kenyi.co.common.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;

import com.google.gson.Gson;
import com.kenyi.co.common.ui.WebActivity;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.okhttp.utils.GsonResultok;
import com.kenyi.co.ui.me.bean.UserFavBean;
import com.kenyi.co.utils.CommonUtils;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.kenyi.co.utils.CommonUtils.getAppVersion;
import static com.kenyi.co.utils.CommonUtils.isFastClick;

public class RouteUtils {

    public static void RoutebyAd(Context TContext, Context mContext, String uri, Map<String, String> params) {

        if (!isFastClick()) {

            return;
        }
        getFav(mContext, params);

        if (uri.contains("http")) {
            System.out.println("包含");
            Intent intentgo1 = new Intent(mContext, WebActivity.class);
            Bundle bundle1 = new Bundle();
//            bundle1.putString("title", params.get("title"));
            bundle1.putString("URL", uri);
            intentgo1.putExtras(bundle1);

            mContext.startActivity(intentgo1);
        } else if (uri.contains("tel")) {

            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse(uri);
            intent.setData(data);
            mContext.startActivity(intent);
        } else {

            if (uri.contains("mqq")) {
                String newuri = uri.replace("mqq", "mqqwpa");

                if (checkAppInstalled(mContext, "com.tencent.mobileqq")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(newuri));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                } else {
                    Intent intentgo1 = new Intent(mContext, WebActivity.class);
                    Bundle bundle1 = new Bundle();
//                    bundle1.putString("title", params.get("url2"));
                    bundle1.putString("URL", params.get("url2"));
                    intentgo1.putExtras(bundle1);
                    mContext.startActivity(intentgo1);
//                    ToastUtil.showShort(TContext, "您未安装qq");
                }
            } else if (uri.contains("taobao")) {

                if (checkAppInstalled(mContext, "com.taobao.taobao")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                } else {
                    Intent intentgo1 = new Intent(mContext, WebActivity.class);
                    Bundle bundle1 = new Bundle();
//                    bundle1.putString("title", params.get("url2"));
                    bundle1.putString("URL", params.get("url2"));
                    intentgo1.putExtras(bundle1);
                    mContext.startActivity(intentgo1);
//                    ToastUtil.showShort(TContext, "您未安装手机淘宝");
                }
            } else if (uri.contains("jdmobile") || uri.contains("jdMobile")) {

                if (checkAppInstalled(mContext, "com.jingdong.app.mall")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                } else {
                    Intent intentgo1 = new Intent(mContext, WebActivity.class);
                    Bundle bundle1 = new Bundle();
//                    bundle1.putString("title", params.get("url2"));
                    bundle1.putString("URL", params.get("url2"));
                    intentgo1.putExtras(bundle1);
                    mContext.startActivity(intentgo1);
//                    ToastUtil.showShort(TContext, "您未安装京东");
                }
            } else if (uri.contains("tmall")) {

                if (checkAppInstalled(mContext, "com.tmall.wireless")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                } else {
                    Intent intentgo1 = new Intent(mContext, WebActivity.class);
                    Bundle bundle1 = new Bundle();

//                    bundle1.putString("title", params.get("url2"));
                    bundle1.putString("URL", params.get("url2"));
                    intentgo1.putExtras(bundle1);
                    mContext.startActivity(intentgo1);
//                    ToastUtil.showShort(TContext, "您未安装天猫");
                }
            } else {

            }

        }

    }

    /**
     * 判断是否安装目标应用
     *
     * @return 是否已安装目标应用
     */
    private static boolean checkAppInstalled(Context context, String pkgName) {
        if (pkgName == null || pkgName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;//true为安装了，false为未安装
        }
    }

    /**
     * 获取偏好
     */
    public static void getFav(final Context context, Map<String, String> params1) {

        Map<String, String> params = new HashMap<>();

        params.put("userId", SharepUtils.getString_info(context, SharepUtils.USER_LOGIN_USERID));
        params.put("deviceId", CommonUtils.getDeviceId(context));
        params.put("articleId", params1.get("articleId"));
        params.put("advid", params1.get("advid"));
        params.put("clickTime", System.currentTimeMillis() + "");
        params.put("adPosition", params1.get("adPosition"));
        params.put("pageName", params1.get("pageName"));
        params.put("appVersion", getAppVersion(context));
        params.put("model", CommonUtils.getSystemModel());
        params.put("os", "Android");
        params.put("osVersion", CommonUtils.getSystemVersion());
        params.put("network", CommonUtils.getNetWorkType(context));

        params.put("screenWidth", CommonUtils.getScreenWidth(context) + "");
        params.put("screenHeight", CommonUtils.getScreenHeight(context) + "");
        params.put("brand", CommonUtils.getDeviceBrand());
        params.put("ip", SharepUtils.getString_info(context, SharepUtils.OUT_IP));
        params.put("carrierName", CommonUtils.getOperator(context));


        Map<String, List<Map>> params2 = new HashMap<>();
        final List<Map> a = new ArrayList();
        a.add(params);


        List<Map> oldData;
        try {
            oldData = SharepUtils.getShDataList(context, SharepUtils.AD_ERROR, Map.class);
            if (oldData!=null&&oldData.size() > 0) {
                for (int i = 0; i < oldData.size(); i++) {
                    a.add(oldData.get(i));
                }
            }
        } catch (Exception e) {

        }
        params2.put("data", a);
        Gson gson = new Gson();
        String str = gson.toJson(params2);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        String url = NetConfig.AD_PUTCLICKLOG;
        OkHttpUtils.postString()
                .url(url)
                .content(str)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        int num = 0;
                        try {
                            GsonResultok packlist = gson.fromJson(response, UserFavBean.class);
                            int code = packlist.getCode();
                            if (code == 200) {

                                SharepUtils.deleleShDataList(context, SharepUtils.AD_ERROR);
                            } else {

                                SharepUtils.setShDataList(context, SharepUtils.AD_ERROR, a);
                            }
                        } catch (Exception e) {
                        }


                    }
                });
    }

    /**
     * 获取偏好
     */
    public static void adPlaylog(final Context context, Map<String, String> params1) {

        Map<String, String> params = new HashMap<>();

        params.put("userId", SharepUtils.getString_info(context, SharepUtils.USER_LOGIN_USERID));
        params.put("deviceId", CommonUtils.getDeviceId(context));
        params.put("articleId", params1.get("articleId"));
        params.put("advid", params1.get("advid"));
        params.put("playTime", System.currentTimeMillis() + "");
        params.put("adPosition", params1.get("adPosition"));
        params.put("pageName", params1.get("pageName"));
        params.put("appVersion", getAppVersion(context));
        params.put("model", CommonUtils.getSystemModel());
        params.put("os", "Android");
        params.put("osVersion", CommonUtils.getSystemVersion());
        params.put("network", CommonUtils.getNetWorkType(context));

        params.put("screenWidth", CommonUtils.getScreenWidth(context) + "");
        params.put("screenHeight", CommonUtils.getScreenHeight(context) + "");
        params.put("brand", CommonUtils.getDeviceBrand());
        params.put("ip", SharepUtils.getString_info(context, SharepUtils.OUT_IP));
        params.put("carrierName", CommonUtils.getOperator(context));
        Map<String, List<Map>> params2 = new HashMap<>();
        final List<Map> a = new ArrayList();
        a.add(params);

        List<Map> oldData;
        try {
            oldData = SharepUtils.getShDataList(context, SharepUtils.AD_PLAY_ERROR, Map.class);
            if (oldData!=null&&oldData.size() > 0) {
                for (int i = 0; i < oldData.size(); i++) {
                    a.add(oldData.get(i));
                }
            }
        } catch (Exception e) {

        }

        params2.put("data", a);
        Gson gson = new Gson();
        String str = gson.toJson(params2);
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        String url = NetConfig.AD_PLAYLOG;

        OkHttpUtils.postString()
                .url(url)
                .content(str)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();

                        int num = 0;
                        try {
                            GsonResultok packlist = gson.fromJson(response, UserFavBean.class);
                            int code = packlist.getCode();
                            if (code == 200) {

                                SharepUtils.deleleShDataList(context, SharepUtils.AD_ERROR);
                            } else {

                                SharepUtils.setShDataList(context, SharepUtils.AD_ERROR, a);
                            }
                        } catch (Exception e) {
                        }


                    }
                });
    }
}
